package cn.wolfcode.wolf2world.service.impl;

import cn.wolfcode.wolf2world.domain.Strategy;
import cn.wolfcode.wolf2world.domain.StrategyTheme;
import cn.wolfcode.wolf2world.query.QueryObject;
import cn.wolfcode.wolf2world.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2world.service.StrategyCatalogService;
import cn.wolfcode.wolf2world.service.StrategyService;
import cn.wolfcode.wolf2world.service.StrategyThemeService;
import cn.wolfcode.wolf2world.utils.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020/8/9 20:09
 */
@Service
public class StrategyThemeServiceImpl implements StrategyThemeService {

    @Autowired
    private StrategyThemeRepository strategyThemeRepository;
    @Autowired
    private StrategyService strategyService;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeRepository.insert(strategyTheme);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        strategyThemeRepository.deleteById(id);
    }

    @Override
    public StrategyTheme get(String id) {
        return strategyThemeRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {
        return strategyThemeRepository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(QueryObject qo) {
        //查询对象
        Query query = new Query();
        return DBHelper.getPage(mongoTemplate, query, qo, StrategyTheme.class, Sort.Direction.ASC, "StrategyTheme");
    }

    /**
     * 添加或更改
     * @param strategyTheme
     */
    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {
        if (StringUtils.hasLength(strategyTheme.getId())) {
            this.update(strategyTheme);
        }else {
            this.save(strategyTheme);
        }

    }

    @Override
    public List<StrategyTheme> queryByDestId(String destId) {
        List<Strategy> list = strategyService.queryByDestId(destId);
        List<StrategyTheme> themes = new ArrayList<>();
        for (Strategy strategy : list) {
            StrategyTheme theme = this.get(strategy.getThemeId());
            themes.add(theme);
        }
        return themes;
    }


}
